 <template>
  <div>
    <div class="cententtable">
      <div @click="switchPlayType(item.id)"
           :class="[active == item.id ? 'active' : 'tabletitle']"
           v-for="item in titlelist"
           :key="item.id">
        {{ item.name }}
      </div>
    </div>
    <div class="tablecontent">
      <div v-show="active == 1"
           class="contentone">
        <textarea v-model="textarea"
                  class="text"></textarea>
        <div class="radiobox">
          <div class="radiobox-item">
            <span>语音:</span>
            <el-select v-model="value"
                       placeholder="请选择">
              <el-option v-for="item in options"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="radiobox-item">
            <span>速度:</span>
            <el-select v-model="value2"
                       placeholder="请选择">
              <el-option v-for="item in options2"
                         :key="item.value2"
                         :label="item.label2"
                         :value="item.value2">
              </el-option>
            </el-select>
          </div>
          <div class="radiobox-item">
            <span>重复:</span>
            <el-select v-model="value3"
                       placeholder="请选择">
              <el-option v-for="item in options3"
                         :key="item.value3"
                         :label="item.label3"
                         :value="item.value3">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="texticon">
          <div>
            <img @click="recordData"
                 src="@/assets/img/记录.png"
                 alt="" /><span>记录</span>
          </div>
          <div>
            <img @click="startPlay"
                 class="play-btn"
                 src="@/assets/img/播放.png"
                 alt="" /><span>播放</span>
          </div>
          <div>
            <img @click="Voiceswitch = true"
                 src="@/assets/img/保存.png"
                 alt="" /><span>保存</span>
          </div>
        </div>
      </div>
      <div v-show="active == 2"
           class="contenttwo">
        <div v-if="Radioswitch"
             class="one">录音广播</div>
        <div v-else
             class="one">实时广播</div>
        <div class="two">00:00:00</div>
        <div class="three"><img src="@/assets/img/音频icon.png"
               alt="" /></div>
        <div v-show="!Radioswitch">
          <div v-show="Voiceswitch"
               class="four">
            <div>
              <img @click="Radioswitch = !Radioswitch"
                   src="@/assets/img/模式切换.png"
                   alt="" /><span>模式切换</span>
            </div>
            <div>
              <img @click="soundRecordBtn('start')"
                   src="@/assets/img/开始录音.png"
                   alt="" /><span>开始录音</span>
            </div>
            <div></div>
          </div>
          <div v-show="!Voiceswitch"
               class="four">
            <div>
              <img @click="Radioswitch = !Radioswitch"
                   src="@/assets/img/模式切换.png"
                   alt="" /><span>模式切换</span>
            </div>
            <div>
              <img @click="soundRecordBtn('stop')"
                   src="@/assets/img/完成录音.png"
                   alt="" /><span>结束录音</span>
            </div>
            <div>
              <img @click="Voiceswitch = true"
                   src="@/assets/img/取消.png"
                   alt="" /><span>取消</span>
            </div>
          </div>
        </div>
        <div v-show="Radioswitch"
             class="four">
          <div>
            <img @click="Radioswitch = !Radioswitch"
                 src="@/assets/img/模式切换.png"
                 alt="" /><span>模式切换</span>
          </div>
        </div>
      </div>
      <div v-show="active == 3"
           class="contentthree">
        <div class="threetitle">
          <span class="threeleft">音频列表:(8条)</span><span class="threeright"><img src="@/assets/img/删除.png"
                 alt="" /></span>
        </div>
        <div class="contentbox">
          <div v-for="(item, index) in audiolist"
               :key="item.id"
               class="videolist">
            <div>
              <span class="indexcss">{{ index + 1 }}</span><span>{{ item.content }}</span>
            </div>
            <div>{{ item.num }}</div>
          </div>
        </div>
        <div class="audioicon">
          <div><img src="@/assets/img/上传.png"
                 alt="" /><span>上传</span></div>
          <div>
            <img @click="BtnStart"
                 src="@/assets/img/播放.png"
                 alt="" /><span>播放</span>
          </div>
          <div>
            <img @click="Voiceswitch = true"
                 src="@/assets/img/循环.png"
                 alt="" /><span>循环</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import CmdReadFileList from '@/utils/cmd_read_file_list';
import { Recorder } from '@/utils/recorder.js'

export default {
  name: "Righttable",
  data () {
    return {
      options: [
        {
          value: "选项1",
          label: "普通话女",
        },
        {
          value: "选项2",
          label: "普通话男",
        },
      ],
      value: "",

      options2: [
        {
          value2: "选项1",
          label2: "x1",
        },
        {
          value2: "选项2",
          label2: "x2",
        },
      ],
      value2: "",

      options3: [
        {
          value3: "选项1",
          label3: "单次",
        },
        {
          value3: "选项2",
          label3: "双次",
        },
      ],
      value3: "",

      titlelist: [
        {
          name: "文字转语音",
          id: "1",
        },
        {
          name: "语音广播",
          id: "2",
        },
        {
          name: "音频文件",
          id: "3",
        },
      ],
      audiolist: [
        {
          id: "1",
          content: "春运宣传.mp3",
          num: "11次",
        },
        {
          id: "2",
          content: "盐城特警.mp3",
          num: "2次",
        },
        {
          id: "3",
          content: "诈骗宣传.mp3",
          num: "8次",
        },
      ],
      active: "1",
      Voiceswitch: true,
      textarea: "科比特",
      Radioswitch: true,

      record: null, //录音对象
      recordmsg: [], //录音内容
      recordbuffer: [] //比特
    };
  },
  methods: {
    // 切换播放类型
    switchPlayType (id) {
      this.active = id;
    },
    // 开始播放
    startPlay () {
      if (this.active === "1") {
        // 播放文字
        this.$emit('playText', this.textarea)
      } else if (this.active === "2") {
        // 播放语音
        console.log('播放语音', this.active);
        this.$emit('playVoice', this.textarea)
      } else if (this.active === "3") {
        // 播放文件
        console.log('播放文件', this.active);
        this.$emit('playFile', this.textarea)
      }
    },
    // 记录数据
    recordData () {
      console.log('记录数据');
    },
    // 录音按钮
    soundRecordBtn (str) {
      // 开始录音
      str !== 'stop' ? this.initAudio() : this.stopAudio();
    },
    stopAudio () {
      let that = this
      if (!that.Voiceswitch && that.record != null) {
        console.log('停止录音', that.record);
        //解决stop报错
        that.Voiceswitch = !that.Voiceswitch
        try {
          that.record.state = "stop"
          console.log('that.record', that.record);
          // that.record.stop();
          // that.record.release();
          // that.record = null
        } catch (e) {
          console.log('e...', e);
          // e.printStackTrace();
        }
      }
    },
    // 初始化录音
    initRecord (rec) {
      let taht = this
      taht.record = null
      taht.record = rec;
    },
    // 判断浏览是否开启麦克风权限
    initAudio () {
      let that = this
      // Older browsers might not implement mediaDevices at all, so we set an empty object first
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }

      // Some browsers partially implement mediaDevices. We can't just assign an object
      // with getUserMedia as it would overwrite existing properties.
      // Here, we will just add the getUserMedia property if it's missing.
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {

          // First get ahold of the legacy getUserMedia, if present
          let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

          // Some browsers just don't implement it - return a rejected promise with an error
          // to keep a consistent interface
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
          }

          // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        }
      }

      navigator.mediaDevices.getUserMedia({ audio: true, video: false })
        .then(function (stream) {
          that.umSuccessCallback(stream)
        })
        .catch(function (err) {
          that.umErrorCallback(err)
        });
    },
    // async shout_producer () {
    //   let that = this
    //   try {
    //     let blob = that.recordmsg.shift()
    //     console.log("blob:", blob);
    //     let arrayBuffer = await that.blob2arraybuffer(blob);
    //     that.recordbuffer.push(...new Uint8Array(arrayBuffer));
    //     setTimeout(() => {
    //       this.shout_producer();
    //       console.log("shout_producer");
    //     }, 1000);
    //   } catch (e) {
    //     console.error(e);
    //   }
    // },
    // async blob2arraybuffer (blob) {
    //   if (!blob) {
    //     return Promise.reject(blob);
    //   }
    //   return new Promise((resolve, reject) => {
    //     let fileReader = new FileReader();
    //     fileReader.onload = () => resolve(fileReader.result);
    //     fileReader.onerror = (e) => reject(e);
    //     fileReader.readAsArrayBuffer(blob);
    //   });
    // },
    // 实时通话成功回调
    umSuccessCallback (stream) {
      console.log('实时通话成功回调...', stream);
      let that = this
      that.Voiceswitch = !that.Voiceswitch
      // 创建一个全局媒体对象
      if (that.record) {
        that.recorder.ondataavailable = (e) => {
          // 获取录制的媒体资源
          console.log('录制中...', e);
        };
        that.recorder.onstop = (e) => {
          // 获取录制的媒体资源
          console.log('录制完毕...', e);
        };
      } else {
        const options = { mimeType: "audio/webm" };
        that.initRecord(new MediaRecorder(stream, options))
      }

      // 绑定媒体对象监听事件

      // 将媒体获取的数据转化为bolo文件类型

      // 将bolo类型转化为成至喇叭能够识别buffer类型

      // 将buffer类型传入mq进行send
      // let that = this
      // let smq = function sendMQTT (msg) {
      //   that.$emit('actualAudio', msg);
      // }

      // this.initRecord(new Recorder(success, smq));
      // this.record.start();
    },
    // 实时通话异常回调
    umErrorCallback (error) {
      switch (error.message || error.name) {
        case 'PERMISSION_DENIED':
        case 'PermissionDeniedError':
          console.info('用户拒绝提供信息。');
          break;
        case 'NOT_SUPPORTED_ERROR':
        case 'NotSupportedError':
          console.info('浏览器不支持硬件设备。');
          break;
        case 'MANDATORY_UNSATISFIED_ERROR':
        case 'MandatoryUnsatisfiedError':
          console.info('无法发现指定的硬件设备。');
          break;
        default:
          console.log('error.code...', error.code);
          console.log('error.name...', error.name);
          console.info('无法打开麦克风。异常信息:' + (error.code || error.name));
          break;
      }
    },
    handleSoundRecording () {
      function getUserMedia (constrains, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
          //最新标准API
          navigator.mediaDevices
            .getUserMedia(constrains)
            .then(success)
            .catch(error);
        } else if (navigator.webkitGetUserMedia) {
          //webkit内核浏览器
          navigator.webkitGetUserMedia(constrains).then(success).catch(error);
        } else if (navigator.mozGetUserMedia) {
          //Firefox浏览器
          navagator.mozGetUserMedia(constrains).then(success).catch(error);
        } else if (navigator.getUserMedia) {
          //旧版API
          navigator.getUserMedia(constrains).then(success).catch(error);
        }
      }

      let _stream = null;
      getUserMedia(
        { video: false, audio: true },
        function (stream) {
          _stream = stream;

          var mediaRecorder = new MediaRecorder(stream);

          console.log("aaa stream:", mediaRecorder.stream);
          // localStream = stream;
          // localVideo.srcObject = stream;
          // localVideo.autoplay = true;
          // localVideo.play();
        },
        function (err) {
          console.log("Failed to get local stream", err);
        }
      );

      setTimeout(() => {
        console.log("setTimeout:", _stream);
        if (_stream) {
          console.log("stream:", _stream);
          _stream.getTracks().forEach(function (track) {
            console.log("stop:", track);
            track.stop();
          });
        }
      }, 4000);

      // var recognition = new (window.SpeechRecognition ||
      //   window.webkitSpeechRecognition ||
      //   window.mozSpeechRecognition ||
      //   window.msSpeechRecognition)();

      // recognition.lang = "cmn-Hans-CN";
      // recognition.interimResults = false;
      // recognition.maxAlternatives = 5;
      // recognition.start();
      // recognition.onresult = function (event) {
      //   console.log("event:", event);
      //   // var color = event.results[0][0].transcript;
      //   // diagnostic.textContent = "Result received: " + color;
      //   // bg.style.backgroundColor = color;
      // };
    },

    BtnStart () {
      console.log('BtnStart');
    },
    handleTtsPlay () {
      // let uint8array = new TextEncoder().encode(this.textarea);
      // let tts = new CmdTtsText(uint8array, "<B250A");
      // let data = tts.pack();
      // let message = Uint8Array.from(data);
      // let servo_angle = new CmdServoAngle(50);
      // let data = servo_angle.pack();

      let read_file_list = new CmdReadFileList();
      let data = read_file_list.pack();
      console.log("pack data:", data);

      let message = Uint8Array.from(data);
      console.log("pack message:", message);

      this.mqtt.client.publish(
        "speak/obtain/PoliceF737",
        message,
        { qos: 0 },
        (e) => {
          console.log("发送指令成功:", e);
        }
      );
    },
  },
  mounted () { },
};
</script>

<style lang="scss" scoped>
.cententtable {
  width: 100%;
  // height: 100%;
  display: flex;
  .tabletitle {
    font-family: MicrosoftYaHei;
    font-size: 16px;
    color: #44c5fd;
    text-align: center;
    font-weight: 400;
    line-height: 40px;
    width: 100%;
    height: 32px;
    line-height: 32px;
    background: rgba(23, 70, 216, 0.2);
    box-shadow: 0 2px 4px 0 rgba(23, 33, 60, 0.5), inset 0 0 4px 0 #00a7ff,
      inset 0 0 16px 0 rgba(33, 137, 255, 0.4);
  }
}
.tablecontent {
  width: 100%;
  height: calc(100%-40px);
  .contentone {
    width: 90%;
    height: 140px;
    padding-top: 5px;
    box-sizing: border-box;
    margin-left: 2%;
    .text {
      width: 364px;
      height: 140px;
      font-family: MicrosoftYaHei;
      font-size: 16px;
      color: #ffffff;
      line-height: 16px;
      font-weight: 400;
      padding: 10px;
      box-sizing: border-box;
      background: rgba(13, 34, 79, 0.75);
      border: 1 solid #43deff;
      border-radius: 1.23px;
      outline: none;
      resize: none;
    }
    .radiobox {
      width: 364px;
      height: 30px;
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #ffffff;
      display: flex;

      .radiobox-item {
        display: flex;
        align-items: center;
        justify-content: center;
        ::v-deep {
          .el-select {
            height: 23px;
            width: 90px;
            margin-left: 8px;
            .el-input {
              height: 100%;
              width: 100%;
              .el-input__inner {
                height: 100%;
                background-color: transparent;
                box-sizing: border-box;
                background: rgba(13, 34, 79, 0.75);
                border: 1px solid #43deff;
                border-radius: 1.23px;
                padding: 0 2px 0px 6px;

                font-family: Microsoft YaHei;
                font-size: 12px;
                color: #ffffff;
              }
              .el-input__suffix {
                right: 0;
                .el-input__suffix-inner {
                  .el-input__icon {
                    line-height: 25px;
                    color: #43deff;
                  }
                }
              }
            }
          }
        }
        &:nth-child(2),
        &:nth-child(3) {
          ::v-deep {
            .el-select {
              width: 57px;
            }
          }
        }
      }

      // /deep/.el-select {
      //   width: 80px !important;
      //   height: 23px !important;
      //   background: rgba(13, 34, 79, 0.65);
      //   border: 1px solid #00ffff;
      //   box-shadow: inset 0 0 7px 0 #00ffff;
      //   border-radius: 2px;
      //   font-family: MicrosoftYaHei;
      //   font-size: 12px;
      //   color: #a1bcbe;
      //   letter-spacing: 0;
      //   font-weight: 400;
      //   .el-input__inner {
      //     background: rgba(13, 34, 79, 0.65);
      //     width: 80px;
      //     height: 23px;
      //     border: none;
      //   }
      // }
      // &::v-deep {
      //   .el-select {
      //     width: 80px;
      //     height: 23px;
      //     // margin-left: 15px;
      //     .el-input--suffix {
      //       width: 100%;
      //       .el-input__icon {
      //         line-height: 23px;
      //       }
      //     }
      //   }
      //   .tagbox {
      //     margin-left: 50px;
      //     margin-top: 10px;
      //     min-height: 100px;
      //     width: 80px;
      //     .el-tag {
      //       border: none;
      //       height: 23px;
      //       color: #00ffff;
      //       .el-icon-close {
      //         margin-top: 14px;
      //         right: 0;
      //       }
      //     }
      //   }
      //   .el-tag {
      //     border: 1px solid #00ffff;
      //     border-radius: 15px;

      //     background: rgba(22, 29, 45, 0);
      //     color: #00ffff;
      //     font-family: MicrosoftYaHei-Bold;
      //     font-size: 14px;
      //     letter-spacing: 0;
      //     font-weight: 700;
      //     padding-left: 5px;
      //   }

      //   .el-select .el-tag__close.el-icon-close::before {
      //     background: #00ffff;
      //     border-radius: 50%;
      //   }
      //   .el-input__inner {
      //     height: 33px !important;
      //     background: rgba(13, 34, 79, 0.75);
      //     border: 1px solid #08c2d1;
      //     font-family: MicrosoftYaHeiUI;
      //     font-size: 16px;
      //     color: #08c2d1;
      //   }
      //   .el-select__input {
      //     background: rgba(22, 29, 45, 0);
      //     border-radius: 2px;
      //     font-family: MicrosoftYaHeiUI;
      //     font-size: 16px;
      //     color: #08c2d1;
      //   }
      //   .el-button {
      //     margin-left: 33px;
      //     background: rgba(0, 34, 140, 0.2);
      //     box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.5), inset 0 0 10px 0 #00b6ff;
      //     border-radius: 6px;
      //     border: none;
      //     color: #01f8f9;
      //     &:hover {
      //       opacity: 0.9;
      //     }
      //   }
      // }
    }
  }
  .texticon {
    width: 100%;
    height: 100px;
    display: flex;
    margin-top: 20px;
    div {
      flex: 1;
      font-family: MicrosoftYaHei;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      font-weight: 400;
      img {
        height: 44px;
        width: 44px;
        cursor: pointer;
      }
      span {
        display: block;
      }
    }
  }
  .contenttwo {
    width: 100%;
    height: 100%;
    .one {
      // width: 96px;
      // height: 24px;
      margin-top: 20px;
      margin-bottom: 15px;
      font-family: MicrosoftYaHei-Bold;
      font-size: 24px;
      color: #ffffff;
      text-align: center;
      line-height: 16px;
      font-weight: 700;
    }
    .two {
      font-family: MicrosoftYaHei;
      font-size: 16px;
      color: #ffffff;
      text-align: center;
      line-height: 16px;
      font-weight: 400;
      margin-bottom: 15px;
    }
    .three {
      width: 350px;
      height: 98px;
      border: 1px solid #3768b3;
      border-radius: 1.62px;
      margin: auto;
      line-height: 120px;
      text-align: center;
    }
    .four {
      width: 100%;
      height: 100px;
      display: flex;
      margin-top: 20px;
      div {
        flex: 1;
        font-family: MicrosoftYaHei;
        font-size: 14px;
        color: #ffffff;
        text-align: center;
        font-weight: 400;
        span {
          display: block;
        }
      }
    }
  }
  .contentthree {
    width: 100%;
    height: 100%;
    .threetitle {
      display: flex;
      justify-content: space-between;
      .threeleft {
        font-family: MicrosoftYaHei;
        font-size: 16px;
        color: #ffffff;
        line-height: 16px;
        font-weight: 400;
      }
    }
    .contentbox {
      width: 372px;
      height: 170px;
      padding: 10px;
      box-sizing: border-box;
      border: 1px solid #3768b3;
      border-radius: 2px;
      margin: auto;
      :hover {
        background-color: #148bff;
      }
      .videolist {
        display: flex;
        justify-content: space-between;
        width: 100%;
        height: 20px;
        font-family: MicrosoftYaHei;
        font-size: 14px;
        color: #ffffff;
        font-weight: 400;
        margin: 8px 0px;
        .indexcss {
          margin-right: 10px;
        }
      }
    }
    .audioicon {
      width: 100%;
      height: 100px;
      display: flex;
      margin-top: 20px;
      div {
        flex: 1;
        font-family: MicrosoftYaHei;
        font-size: 14px;
        color: #ffffff;
        text-align: center;
        font-weight: 400;
        span {
          display: block;
          font-family: MicrosoftYaHei;
          font-size: 14px;
          color: #ffffff;
          text-align: center;
          font-weight: 400;
        }
      }
    }
  }
}
.active {
  font-family: MicrosoftYaHei;
  font-size: 16px;
  color: #44c5fd;
  text-align: center;
  font-weight: 400;
  line-height: 40px;
  width: 100%;
  height: 32px;
  line-height: 32px;
  background: #2c86cd;
  background: rgba(23, 70, 216, 0.2);
  box-shadow: 0 1px 3px 0 rgba(23, 33, 60, 0.5), inset 0 0 3px 0 #00a7ff,
    inset 0 0 10px 0;
}
</style>
